
/**
 * @class $$.data.Reader
 * @extends $$.data.SQL 
 * 生成查询数据库的SQL语句。CRUD的Read部分在这里完成，包括分页。
 */
$$.data.SqlReader = function(){
	this.sqlParser = new $$.sql.Parser();
}
;(function(){
	$$.data.SqlReader.prototype = {
		 read : function(sql){
			 var 
	    		 sqlMgr = this.sqlParser
				,sqlMgr = sqlMgr.parse(sql)
	            ,field	= sqlMgr.getFields()
	            ,sql	= isPage ? sqlMgr.autoClass(sql) : sql
	            ,isPage = isPage ? this.page(sql, sqlMgr.getSortField(), true) : null
	            ,rsObj 	= $$.sql(isPage ? isPage.sql : sql).rsObj;
		 
		 	return 
		 }
		,list : function(rsObj, sqlMgr){
	        var 
	        	 rawArr	= rsObj.getRows().toArray()
	        	,fields = rsObj.Fields
	        	,fLen 	= fields.Count
				,len  	= rawArr.length / fLen
				,data
				,sp
				,list	= [];
					
	        	rsObj.Close();
				
			for (var i = 0; i < len; i++) {
				data = {};
				sp = i * fLen;
				for (var j = 0; j < fLen; j++){
					data[fields(j).name] = sqlMgr.sql2jsValue(rawArr[sp + j], fields);
				}
				list.push(data);
			}
			
			return list;
		 }
	};
})();
Object.extend($$.data.SQL, $$.data.SqlReader);


/**
 * @class $$.data.ADO_Reader
 * @extends $$.data.SQL 
 */
$$.data.ADO_Reader = function(){
	
}
;(function(){
	function adoPaging(){
		var 
			 sql		= this.sql
			,arr		= sql.match(/SELECT\s+(.*)\s+FROM\s+(\w+)\s?/i)
			,id_Only	= sql.replace(arr[1], arr[2] + '.ID')
			,Rs			= Server.CreateObject ("ADODB.Recordset")
			,Rs			= Rs.Open(id_Only, $$.sql().connObj, 1 ,1) || Rs
			,Rs			= Rs.EOF && Rs.BOF ? (function(){
				Response.write('没有记录'); throw '没有记录';
				})(): Rs
			,IDs		= []
			,pageSize	= this.pageSize
			,totalCount	= Rs.recordcount // 总数 
			,page		= (start / pageSize) + 1
			,page		= page || 1
			,page		= (page - totalCount) > 0 ? totalCount : page
			,j			= totalCount
			,j			= j - (page - 1) * pageSize
			,i			= 0;
	
		Rs.pagesize    = pageSize;
		Rs.absolutepage = page;
		do {
			IDs.push(Rs('id').value);
//			Response.Write("<p>每条记录信息：" + Rs("id")  + "</p>");
			i++;
			Rs.movenext();
		}while (!Rs.Eof && ( i < pageSize));
	    Rs.close();
	    
		var 
		 	 IDs		= (/\s+WHERE\s+/i.test(sql) ?　" AND " : " WHERE ") + "  news.ID = " + IDs.join(' OR news.ID = ')
		 	,hasSort	= /(\s+ORDER\s+BY\s+[\w\.]+)\s?(ASC|DESC)?/i;
		
		if(!hasSort.test(sql)){
			 sql += IDs;
		}else{
			 IDs += " $1 ASC "; // 必须相反，与原来的ORDER BY！
			 sql = sql.replace(hasSort, IDs);  
		}
	}
	
	$$.data.ADO_Reader.prototype = {
		// @override
		page : adoPaging
	};
})();
Object.extend($$.data.SqlReader, $$.data.ADO_Reader);